<template>
  <div>
    <!-- 表单 -->
    <FormPanel ref="form" :cols="4" :list="list" :isSubmitBtn="false" @formChange="formChange"></FormPanel>
    <!-- 操作按钮 -->
    <ButtonArea :containerStyle="{ paddingLeft: '80px' }">
      <el-button size="small" type="primary" :disabled="newBtnDisabled" @click="newHandle()">新建</el-button>
      <el-button size="small" type="primary" :disabled="obsoleteBtnDisabled" @click="obsoleteHandle()">作废</el-button>
      <AjaxButton size="small" type="primary" icon="el-icon-folder" :disabled="saveBtnDisabled" :click="saveHandle">保存</AjaxButton>
      <el-button size="small" type="primary" icon="el-icon-refresh-left" :disabled="cancelBtnDisabled" @click="cancelHandle()">取消</el-button>
      <el-button size="small" type="primary" icon="el-icon-printer" :disabled="prindfBtnDisabled" @click="prindfHandle()">打印报价单</el-button>
      <el-button size="small" type="primary" icon="el-icon-folder" :disabled="completeBtnDisabled" @click="completeHandle()">完成</el-button>
    </ButtonArea>
    <!-- 表格 -->
    <FilterTable
      ref="table"
      columnsRef="partPartOutboundPartSalesQuoteIndex"
      :columns="columns"
      selectionType="single"
      :dataSource="dataSource"
      :onCellChange="onCellChange"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
    >
      <template slot="moreActions">
        <span @click="() => deleteHandle()">删除数据</span>
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" :disabled="addBtnDisabled" @click="handleNew">新增</el-button>
        <el-button size="small" type="primary" :disabled="exportBtnDisabled" :loading="exportLoading" @click="exportFun">导出</el-button>
        <el-button size="small" type="primary" :disabled="importSalesOrderBtnDisabled" @click="isShowPartSalesOrder = true">引进销售单</el-button>
        <el-button size="small" type="primary" :disabled="exportSalesOrderBtnDisabled" @click="exportToSalesOrder">导出销售单</el-button>
      </template>
    </FilterTable>
    <!-- 配件报价单选择 -->
    <BaseDialog title="配件报价单选择" :visible.sync="isShowquotationNumber" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <quotationNumber :orederNo="orederNo" @confirm="confirmQuotationNumber" @cancel="isShowquotationNumber = false" />
    </BaseDialog>
    <!-- 配件销售单选择 -->
    <BaseDialog title="配件销售单选择" :visible.sync="isShowPartSalesOrder" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partSalesOrder @confirm="confirmPartSalesOrder" @cancel="isShowPartSalesOrder = false" />
    </BaseDialog>
    <!-- 客户选择 -->
    <BaseDialog title="客户选择" :visible.sync="isShowcustomerChoice" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <customerChoice @confirm="confirmCustomerChoice" @cancel="isShowcustomerChoice = false" />
    </BaseDialog>
    <!-- 选择车主 -->
    <BaseDialog title="选择车主" :visible.sync="isShowchooseOwner" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <chooseOwner @confirm="confirmChooseOwner" @cancel="isShowchooseOwner = false" />
    </BaseDialog>
    <!-- 配件销售报价 -->
    <Drawer title="新建配件销售报价" :visible.sync="isShowAddpartSalesQuote" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddpartSalesQuote :cunData="cunData" :rate="tax" @confirm="confirmAddPartSalesQuote" @cancel="isShowAddpartSalesQuote = false" />
    </Drawer>

    <!-- 打印 -->
    <div v-if="printFlag">
      <BasePrint
        ref="print"
        :data="printList"
        :printerType="printParams.vPrintType ? (printParams.vPrintType == 99901002 ? 'stylus' : 'laser') : 'stylus'"
        :alwaysPrint="printParams.vPageType ? (printParams.vPageType == 99911002 ? true : false) : true"
        :printCopies="printParams.nPages || 1"
        :direction="printParams.vPageDirection == 99921001 ? 'horizontal' : 'vertical'"
        :directPrint="printParams.vDirectPrint ? (printParams.vDirectPrint == 1 ? true : false) : true"
        :isDuplex="printParams.vBothPrint == 1 ? true : false"
        template="templatePartSalesQuote"
      />
    </div>
  </div>
</template>

<script>
import * as Util from '@/utils/index.js';
import moment from 'moment';
import quotationNumber from './components/quotationNumber';
import partSalesOrder from './components/searchSalesOrder';
import customerChoice from './components/customerChoice';
import chooseOwner from './components/chooseOwner';
import AddpartSalesQuote from './components/AddpartSalesQuote';
import { dictionary } from '@/utils/dictMixin';
import { querySalesQutationDetail, handleSave, handleDelete, finished, partSalesQteExport } from '@/api/part/partOutbound/partSalesQuote/index.js';
import { getCangKuSelect } from '@/api/part/partOutbound/repairMaterials/dict.js';
import { findAllRepair } from '@/api/repair/basicParameters';
import { queryUnitCode } from '@/api/part/partInfo';
import { partSalesItem, save } from '@/api/part/partOut/partSales/index';
import { getUser } from '@/assets/js/auth';
import { exportExcelFile } from '@/utils/index';
import { dealerPrintApi } from '@/api/repair/index.js';

export default {
  name: 'partSalesQuote',
  components: {
    quotationNumber,
    partSalesOrder,
    customerChoice,
    chooseOwner,
    AddpartSalesQuote
  },
  mixins: [dictionary],
  data() {
    this.baseTable = null;
    return {
      typeHandle: '客户名称',
      cunId: [],
      totaloutAmount: '',
      totalcostAmount: '',
      cunData: {}, // 存带过去的信息
      list: this.createList(),
      columns: this.createColumns(),
      dataSource: [],
      rowSelect: [],
      /** 模态框 状态 */
      isShowquotationNumber: false,
      isShowcustomerChoice: false,
      isShowchooseOwner: false,
      isShowAddpartSalesQuote: false,
      isShowPartSalesOrder: false,
      /** 按钮状态 */

      // 表格里
      addBtnDisabled: false, // 新增
      exportBtnDisabled: false, // 导出
      importSalesOrderBtnDisabled: false, // 引进销售单
      exportSalesOrderBtnDisabled: true, // 导出销售单
      delDisabled: false, // 是否可以删除
      // 下面  按钮控制
      newBtnDisabled: false, // 新建
      obsoleteBtnDisabled: false, // 作废
      saveBtnDisabled: false, // 保存
      cancelBtnDisabled: false, // 取消
      prindfBtnDisabled: false, // 打印
      completeBtnDisabled: false, // 完成
      // 控制操作按钮
      customerNo: '', // 存车主和客户的
      tax: '', // 税率
      printFlag: false,
      printList: {},
      exportLoading: false,
      delId: '',
      printParams: {} // 打印参数
    };
  },
  computed: {
    orederNo() {
      return this.list.find(x => x.fieldName == 'quoteNo').initialValue;
    }
  },
  mounted() {
    this.baseTable = this.$refs.table.$refs.pageTable;
    this.stateControl('none');
    this.queryUnitCode();
    this.getCangKuSelect();
    this.findAllRepair();
    this.queryPrintParams();
  },
  methods: {
    // 新增的逻辑判断
    handleNew() {
      if (this.list.find(x => x.fieldName === 'customerName').label == '客户名称') {
        if (
          this.list.find(x => x.fieldName === 'customerName').initialValue == '' ||
          this.list.find(x => x.fieldName === 'customerName').initialValue == undefined ||
          this.list.find(x => x.fieldName === 'customerName').initialValue == null
        ) {
          this.$notify({
            title: '提示',
            message: '客户名称未选择',
            type: 'warning'
          });
        } else {
          this.isShowAddpartSalesQuote = true;
        }
      } else {
        if (
          this.list.find(x => x.fieldName === 'customerName').initialValue == '' ||
          this.list.find(x => x.fieldName === 'customerName').initialValue == undefined ||
          this.list.find(x => x.fieldName === 'customerName').initialValue == null
        ) {
          this.$notify({
            title: '提示',
            message: '车主未选择',
            type: 'warning'
          });
        } else {
          this.isShowAddpartSalesQuote = true;
        }
      }
    },
    // 保存
    async handleSave(val) {
      console.log(val, '111');
      const res = await handleSave(val);
      if (res.resultCode == 200) {
        this.list.find(x => x.fieldName == 'quoteNo').initialValue = res.data;
        this.stateControl('save');
        this.$notify({
          title: '提示',
          message: '保存成功',
          type: 'success'
        });
        // this.$refs.form.RESET_FORM()
        // 删除完重置
        this.cunId = [];
        this.baseTable.EXECUTE_DELETE(this.dataSource);
        let params = { salesQuoteNo: res.data };
        this.querySalesQutationDetail(params);
      }
    },
    // 作废
    handleDelete(val) {
      this.$confirm('此操作将作废该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await handleDelete(val);
          if (res.resultCode == 200) {
            this.stateControl('obsole');
            this.$notify({
              title: '提示',
              message: '作废成功',
              type: 'success'
            });
          } else {
            this.$notify.error({ title: '提示信息', message: '作废失败!' });
          }
        })
        .catch(() => {
          this.$notify.error({ title: '提示信息', message: '已取消作废' });
        });
    },
    // 获取税率
    async findAllRepair() {
      let re = await findAllRepair();
      this.tax = re.data['1003'];
    },

    // 单位下拉框
    async queryUnitCode() {
      const res3 = await queryUnitCode();
      this.columns.find(item => item.dataIndex == 'unitCode').filterItems = this.columns.find(item => item.dataIndex == 'unitCode').editItems = res3.data.map(x => ({
        text: x.UNIT_NAME,
        value: x.UNIT_CODE
      }));
    },
    // 表格数据变化时
    onCellChange(val, val2) {
      // if (
      //   this.list.find(x => x.fieldName === 'quoteNo').initialValue != null &&
      //   this.list.find(x => x.fieldName === 'quoteNo').initialValue != '' &&
      //   this.list.find(x => x.fieldName === 'quoteNo').initialValue != undefined
      // ) {
      //   this.saveBtnDisabled = false; // 保存
      // }
      // costAmount不含税金额
      // costPrice 不含税单价
      // outQuantity销售数量
      // outPrice 销售单价
      // outAmount销售金额
      // tax 税
      let costAmount = this.dataSource[val2.$index].costAmount;
      let costPrice = this.dataSource[val2.$index].costPrice;
      let outQuantity = this.dataSource[val2.$index].outQuantity;
      let outPrice = this.dataSource[val2.$index].outPrice;
      let outAmount = this.dataSource[val2.$index].outAmount;
      let tax = Number(this.tax);
      if (isNaN(Number(outPrice))) {
        outPrice = 0.0;
      } else {
        outPrice = Number(outPrice).toFixed(2);
      }
      if (isNaN(Number(outQuantity))) {
        outQuantity = 0.0;
      } else {
        outQuantity = Number(outQuantity).toFixed(2);
      }
      costPrice = (Number(outPrice) / (1 + tax)).toFixed(2);
      costAmount = (Number(costPrice) * Number(outQuantity)).toFixed(2);
      outAmount = (Number(outPrice) * Number(outQuantity)).toFixed(2);

      this.dataSource[val2.$index].costAmount = costAmount;
      this.dataSource[val2.$index].costPrice = costPrice;
      this.dataSource[val2.$index].outQuantity = outQuantity;
      this.dataSource[val2.$index].outPrice = outPrice;
      this.dataSource[val2.$index].outAmount = outAmount;
      //  这里就开始计算total   用来储存
      this.totaloutAmount = 0;
      this.totalcostAmount = 0;
      this.dataSource.forEach(x => {
        this.totaloutAmount = this.totaloutAmount + Number(x.outAmount);
        this.totalcostAmount = this.totalcostAmount + Number(x.costAmount);
      });
    },
    // 仓库数据
    async getCangKuSelect() {
      const res = await getCangKuSelect();
      let storageDataList = res.data.map(x => ({
        value: x.STORAGE_CODE,
        text: x.STORAGE_NAME
      }));
      this.columns.find(x => x.dataIndex === 'storageCode').filterItems = this.columns.find(x => x.dataIndex === 'storageCode').editItems = this.storageList = storageDataList;
    },
    // 订单明细
    async querySalesQutationDetail(val) {
      const res = await querySalesQutationDetail(val.salesQuoteNo);
      if (res.resultCode == 200) {
        res.data.forEach(x => {
          let costAmount = x.costAmount;
          let costPrice = x.costPrice;
          let outQuantity = x.outQuantity;
          let outPrice = x.outPrice;
          let outAmount = x.outAmount;
          let tax = Number(this.tax);
          if (isNaN(Number(outPrice))) {
            outPrice = 0.0;
          } else {
            outPrice = Number(outPrice).toFixed(2);
          }
          if (isNaN(Number(outQuantity))) {
            outQuantity = 0.0;
          } else {
            outQuantity = Number(outQuantity).toFixed(2);
          }
          costPrice = (Number(outPrice) / (1 + tax)).toFixed(2);
          costAmount = (Number(costPrice) * Number(outQuantity)).toFixed(2);
          outAmount = (Number(outPrice) * Number(outQuantity)).toFixed(2);

          x.costAmount = costAmount;
          x.costPrice = costPrice;
          x.outQuantity = outQuantity;
          x.outPrice = outPrice;
          x.outAmount = outAmount;
        });

        //  这里就开始计算total   用来储存
        this.totaloutAmount = 0;
        this.totalcostAmount = 0;
        this.dataSource.forEach(x => {
          this.totaloutAmount = this.totaloutAmount + Number(x.outAmount);
          this.totalcostAmount = this.totalcostAmount + Number(x.costAmount);
        });

        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(res.data);

        if (val.isFinished == '10041002') {
          this.newBtnDisabled = true; // 新建
          this.obsoleteBtnDisabled = false; // 作废
          this.saveBtnDisabled = false; // 保存
          this.cancelBtnDisabled = false; // 取消
          this.prindfBtnDisabled = true; // 打印
          this.completeBtnDisabled = true; // 完成
          this.delDisabled = false;
          this.addBtnDisabled = false; // 新增
          this.exportBtnDisabled = true; // 导出
          this.importSalesOrderBtnDisabled = true; // 引进销售单
          this.exportSalesOrderBtnDisabled = false; // 导出销售单
        }
        if (val.isFinished == '10041001') {
          this.delDisabled = true;
          this.list.find(x => x.fieldName === 'quoteDate').disabled = true;
          this.columns.find(x => x.dataIndex === 'outPrice').disabled = true;
          this.columns.find(x => x.dataIndex === 'outQuantity').disabled = true;
          this.newBtnDisabled = true; // 新建
          this.obsoleteBtnDisabled = true; // 作废
          this.saveBtnDisabled = true; // 保存
          this.cancelBtnDisabled = false; // 取消
          this.prindfBtnDisabled = false; // 打印
          this.completeBtnDisabled = true; // 完成

          this.addBtnDisabled = true; // 新增
          this.exportBtnDisabled = false; // 导出
          this.importSalesOrderBtnDisabled = true; // 引进销售单
          this.exportSalesOrderBtnDisabled = true; // 导出销售单
        }
      }
    },
    // 新建按钮方法
    newHandle() {
      //  this.ceShi('ceshi')
      this.stateControl('new');
    },
    // 保存按钮方法
    saveHandle() {
      this.saveBtnDisabled = true;
      this.$refs.form.SUBMIT_FORM();
    },
    // 作废按钮方法
    obsoleteHandle() {
      let x = {
        salesPart_quotaion: this.dataSource,
        quoteNo: this.list.find(x => x.fieldName === 'quoteNo').initialValue
      };
      this.handleDelete(x);
    },
    // 打印按钮方法
    async prindfHandle() {
      let quoteNo = this.list.find(x => x.fieldName === 'quoteNo').initialValue;
      let customerName = this.list.find(x => x.fieldName === 'customerName').initialValue;
      let res = await querySalesQutationDetail(quoteNo);
      if (res.data.length) {
        this.printList = res;
        this.printList['quoteNo'] = quoteNo;
        this.printList['customerName'] = customerName;
        this.printList['ysr'] = getUser();
        this.stateControl('prindf');
      }
    },
    // 取消按钮方法
    cancelHandle() {
      this.stateControl('cancel');
    },
    // 完成按钮方法
    completeHandle() {
      this.finished();
    },
    async finished() {
      const res = await finished({ quoteNo: this.list.find(x => x.fieldName === 'quoteNo').initialValue });
      if (res.resultCode == 200) {
        this.stateControl('complete');
        this.$notify({
          title: '提示',
          message: '完成成功',
          type: 'success'
        });
      }
    },
    // 配件报价单选择 确定方法
    confirmQuotationNumber(val) {
      this.isShowquotationNumber = false;
      this.list.find(x => x.fieldName === 'quoteNo').initialValue = val[0].salesQuoteNo; // 报价单号
      this.list.find(x => x.fieldName === 'quoteNo').disabled = true;
      this.list.find(x => x.fieldName === 'wu11').disabled = true;
      this.list.find(x => x.fieldName === 'customerName').initialValue = val[0].customerName; // 客户
      this.list.find(x => x.fieldName === 'quoteDate').initialValue = val[0].salesQuoteDate; // 日期
      this.customerNo = val[0].customerCode;
      this.querySalesQutationDetail(val[0]);
    },
    // 导出到配件销售单
    async exportToSalesOrder() {
      let list = [];
      let salesAllAmount = 0;
      this.dataSource.forEach(x => {
        // 转换字段驼峰发送请求到DTO
        let itemList = {
          salesType: 80961001,
          storageCode: x.storageCode,
          storagePositionCode: x.storagePositionCode,
          partNo: x.partNo,
          partName: x.partName,
          unitCode: x.unitCode,
          partQuantity: x.outQuantity,
          partSalesPrice: x.outPrice,
          salesAmount: x.outAmount,
          partSalesAmount: x.outAmount,
          discount: 1,
          oldSalesPartNo: null,
          priceType: x.priceType,
          priceRate: x.priceRate,
          partCostPrice: x.costPrice ? x.costPrice : 0,
          isFinished: 10041002,
          partCostAmount: x.costAmount,
          itemId: null
        };
        list.push(itemList);
        salesAllAmount = salesAllAmount + Number(x.outAmount);
      });
      let result = await save({
        partSalestable: list,
        customerCode: this.customerNo,
        customerName: this.list.find(x => x.fieldName === 'customerName').initialValue,
        balanceStatus: 10041002,
        salesPartAmount: salesAllAmount
      });
      console.log(result);
      if (result.resultCode == 200) {
        return this.$notify.success({ title: '提示信息', message: '导出销售单完成，单号：' + result.data });
      }
    },
    // 配件销售单选择 确定方法
    async confirmPartSalesOrder(val) {
      this.isShowPartSalesOrder = false;
      this.stateControl('new');
      this.list.find(x => x.fieldName === 'customerName').initialValue = val.CUSTOMER_NAME; // 客户
      this.customerNo = val.CUSTOMER_CODE;
      // this.querySalesQutationDetail(val[0].salesQuoteNo);
      let res = await partSalesItem(val.SALES_PART_NO);
      console.log(res);
      if (res.resultCode == 200) {
        let resData = res.data;
        this.jsonToHump(resData);
        console.log(resData);
        resData.forEach(x => {
          let costAmount = x.partCostAmount;
          let costPrice = x.partCostPrice;
          let outQuantity = x.partQuantity;
          let outPrice = x.partSalesPrice;
          let outAmount = x.salesAmount;
          let tax = Number(this.tax);
          if (isNaN(Number(outPrice))) {
            outPrice = 0.0;
          } else {
            outPrice = Number(outPrice).toFixed(2);
          }
          if (isNaN(Number(outQuantity))) {
            outQuantity = 0.0;
          } else {
            outQuantity = Number(outQuantity).toFixed(2);
          }
          costPrice = (Number(outPrice) / (1 + tax)).toFixed(2);
          costAmount = (Number(costPrice) * Number(outQuantity)).toFixed(2);
          outAmount = (Number(outPrice) * Number(outQuantity)).toFixed(2);

          x.costAmount = costAmount;
          x.costPrice = costPrice;
          x.outQuantity = outQuantity;
          x.outPrice = outPrice;
          x.outAmount = outAmount;
        });
        //  这里就开始计算total   用来储存
        this.totaloutAmount = 0;
        this.totalcostAmount = 0;
        this.dataSource.forEach(x => {
          this.totaloutAmount = this.totaloutAmount + Number(x.outAmount);
          this.totalcostAmount = this.totalcostAmount + Number(x.costAmount);
        });
        this.baseTable.EXECUTE_INSERT(resData);
      }
    },
    // 字符串的下划线格式转驼峰格式，eg：hello_world => helloWorld
    underline2Hump(str) {
      var str1 = str.toLowerCase();
      while (str1.indexOf('_') != -1) {
        str1 = str1.replace(/_\w/, str1.substr(str1.indexOf('_') + 1, 1).toUpperCase());
      }
      return str1;
    },
    // JSON对象的key值转换为驼峰式
    jsonToHump(obj) {
      if (obj instanceof Array) {
        obj.forEach((v, i) => {
          this.jsonToHump(v);
        });
      } else if (obj instanceof Object) {
        Object.keys(obj).forEach(key => {
          var newKey = this.underline2Hump(key);
          if (newKey !== key) {
            obj[newKey] = obj[key];
            delete obj[key];
          }
          this.jsonToHump(obj[newKey]);
        });
      }
    },
    // 选择车主 确定方法
    confirmChooseOwner(val) {
      this.isShowchooseOwner = false;
      this.list = [...this.list];
      console.log(val, val[0].ownerName, '车主');
      // this.list.find(x => x.fieldName === 'customerName').initialValue = val[0].ownerName;
      this.list.find(x => x.fieldName === 'customerName').initialValue = val[0].ownerName;
      this.customerNo = val[0].ownerCode;
      this.cunData = val[0];
      this.list = [...this.list];
    },
    // 客户选择  确定方法
    confirmCustomerChoice(val) {
      // 表格添加一条数据
      console.log('chuaguolaide');
      console.log(val);
      this.isShowcustomerChoice = false;
      this.list = [...this.list];
      this.list.find(x => x.fieldName === 'customerName').initialValue = val[0].CUSTOMER_NAME;
      this.customerNo = val[0].CUSTOMER_CODE;
      console.log(this.list.find(x => x.fieldName === 'customerName').initialValue, '111');
      this.cunData = val[0];
      this.list = [...this.list];
      // this.$notify.success({
      //   title: '提示',
      //   message: '添加成功',
      // });
    },
    // 新增配件销售报价  确定方法
    confirmAddPartSalesQuote(val) {
      let data = Util.camelCaseObject(val);
      for (const item of this.dataSource) {
        if (item.partNo == data.partNo && item.storageCode == data.storageCode) {
          return this.$notify.error({ title: '提示信息', message: '不能添加相同的配件！' });
        }
      }
      data.costPrice = (Number(data.outPrice) / (1 + Number(this.tax))).toFixed(2);
      data.costAmount = (Number(data.costPrice) * Number(data.outQuantity)).toFixed(2);
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
      this.$notify.success({ title: '提示信息', message: '添加成功！' });
    },
    // 表单的方法
    formChange(val) {
      console.log(this.list.find(x => x.fieldName === 'quoteDate').initialValue, '111111111DATA');

      this.dataSource.forEach(x => {
        if (x.itemId == null || x.itemId == '' || x.itemId == undefined) {
          x.flag = 'A';
          x.itemId = '';
        } else {
          x.flag = 'X';
        }
        if (x.outPrice == null || x.outPrice == '' || x.outPrice == undefined) {
          x.outPrice = '0.00';
        }
        if (x.outQuantity == null || x.outQuantity == '' || x.outQuantity == undefined) {
          x.outQuantity = '0.00';
        }
      });
      let x = {
        // 要保存的数据
        // salesPart : this.dataSource,
        salesPart_quotaion: this.dataSource.map(item => {
          const item2 = Object.assign({}, item);
          return item2;
        }),
        quoteNo: this.list.find(x => x.fieldName === 'quoteNo').initialValue,
        customerName: this.list.find(x => x.fieldName === 'customerName').initialValue,
        customerCode: this.customerNo,
        quoteDate: moment(this.list.find(x => x.fieldName === 'quoteDate').initialValue).format('YYYY-MM-DD'),
        delID: this.cunId ? this.cunId.join(',') : '', // 删除的id
        outAmounnt: this.totaloutAmount,
        costAmounnt: this.totalcostAmount
      };
      this.handleSave(x);
    },
    createList() {
      return [
        {
          type: 'INPUT',
          label: '报价单号',
          fieldName: 'quoteNo',
          disabled: false,
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.isShowquotationNumber = true;
                }}
              ></el-button>
            );
          }
        },
        {
          type: 'SELECT',
          label: '选择类型',
          fieldName: 'wu11',
          disabled: false,
          itemList: [
            { value: '1', text: '客户' },
            { value: '2', text: '车主' }
          ],
          initialValue: '1',
          change: val => {
            // console.log(val, 'val');
            this.list.find(item => item.fieldName == 'customerName').initialValue = '';
            if (val == '1') {
              this.typeHandle = '客户名称';
              this.list.find(x => x.fieldName === 'customerName').label = '客户名称';
              this.list = [...this.list];
            } else if (val == '2') {
              this.typeHandle = '车主';
              this.list.find(x => x.fieldName === 'customerName').label = '车主';
              this.list = [...this.list];
            }
          }
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          readonly: true,
          rules: [{ required: true, message: '这是必填字段', trigger: 'input' }],
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  if (this.typeHandle == '客户名称') {
                    this.isShowcustomerChoice = true;
                  } else {
                    this.isShowchooseOwner = true;
                  }
                }}
              ></el-button>
            );
          }
        },
        {
          type: 'DATE',
          label: '报价日期',
          disabled: false,
          fieldName: 'quoteDate'
          // rules: [{ required: true, message: '这是必填字段', trigger: 'blur' }]
        }
      ];
    },
    createColumns() {
      return [
        {
          title: '序号',
          width: 50,
          dataIndex: 'xuhao',
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '仓库',
          minWidth: 150,
          dataIndex: 'storageCode',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '库位',
          minWidth: 120,
          dataIndex: 'storagePositionCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单位',
          dataIndex: 'unitCode',
          disabled: true,
          editable: true,
          editType: 'select',
          editItems: [],
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '销售单价',
          dataIndex: 'outPrice',
          editable: true,
          editType: 'number',
          precision: 2,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税单价',
          dataIndex: 'costPrice',
          disabled: true,
          editable: true,
          editType: 'number',
          precision: 2,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '销售数量',
          dataIndex: 'outQuantity',
          editable: true,
          editType: 'number',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '销售金额',
          dataIndex: 'outAmount',
          editable: true,
          disabled: true,
          editType: 'number',
          precision: 2,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税金额',
          dataIndex: 'costAmount',
          editable: true,
          disabled: true,
          editType: 'number',
          precision: 2,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
        }
      ];
    },
    // 操作删除接口
    Obsolete(val) {
      if (val.itemId != null && val.itemId != undefined && val.itemId != '') {
        this.cunId.push(val.itemId);
      }
      this.dataSource.splice(val.index, 1);
    },
    onRowSelectChange(rows) {
      console.log('选择的行', rows);
      this.rowSelect = rows;
    },
    deleteHandle() {
      let dele = [];
      let retain = [];
      for (const item of this.rowSelect) {
        if (item.isFinished == 10041001) {
          retain.push(item.partName);
        } else {
          dele.push(item);
          if (item.itemId != null && item.itemId != undefined && item.itemId != '') {
            this.cunId.push(item.itemId);
          }
        }
      }
      if (dele.length == 0) {
        return this.$notify.error({ title: '提示信息', message: '没有可以删除的配件!' });
      }
      if (retain.length > 0) {
        let str = retain.join('，');
        this.$notify.warning({ title: '提示信息', message: `配件${str}已完成，无法删除！` });
      }
      this.baseTable.EXECUTE_DELETE(dele);
      this.$notify.success({ title: '提示信息', message: `删除成功！` });
    },
    // 全局状态控制方法
    stateControl(val) {
      if (val == 'none' || val == 'complete' || val == 'obsole') {
        // 初始化
        this.newBtnDisabled = false; // 新建
        this.obsoleteBtnDisabled = true; // 作废
        this.saveBtnDisabled = true; // 保存
        this.cancelBtnDisabled = false; // 取消
        this.prindfBtnDisabled = true; // 打印
        this.completeBtnDisabled = true; // 完成

        this.addBtnDisabled = true; // 新增
        this.exportBtnDisabled = true; // 导出
        this.importSalesOrderBtnDisabled = false; // 引进销售单
        this.exportSalesOrderBtnDisabled = true; // 导出销售单

        this.list.find(x => x.fieldName === 'quoteNo').disabled = false;
        this.list.find(x => x.fieldName === 'customerName').disabled = true;
        this.list.find(x => x.fieldName === 'quoteDate').disabled = false;
        this.list.find(x => x.fieldName === 'wu11').disabled = false;

        this.dataSource = [];
        this.list.find(x => x.fieldName === 'quoteNo').initialValue = '';
        this.list.find(x => x.fieldName === 'customerName').initialValue = undefined;
        this.list.find(x => x.fieldName === 'quoteDate').initialValue = '';
        this.$refs.form.RESET_FORM();
      } else if (val == 'new') {
        // 新建
        this.newBtnDisabled = true; // 新建
        this.obsoleteBtnDisabled = true; // 作废
        this.saveBtnDisabled = false; // 保存
        this.cancelBtnDisabled = false; // 取消
        this.prindfBtnDisabled = true; // 打印
        this.completeBtnDisabled = true; // 完成

        this.addBtnDisabled = false; // 新增
        this.exportBtnDisabled = true; // 导出
        this.importSalesOrderBtnDisabled = true; // 引进销售单
        this.exportSalesOrderBtnDisabled = true; // 导出销售单

        this.list.find(x => x.fieldName === 'quoteNo').disabled = true;
        this.list.find(x => x.fieldName === 'customerName').disabled = false;
        this.list.find(x => x.fieldName === 'quoteDate').disabled = false;
        this.list.find(x => x.fieldName === 'wu11').disabled = false;
        this.list.find(x => x.fieldName === 'quoteDate').initialValue = new Date();
      } else if (val == 'save') {
        // 保存
        this.list.find(x => x.fieldName === 'quoteNo').disabled = true;
        this.list.find(x => x.fieldName === 'customerName').disabled = true;
        this.list.find(x => x.fieldName === 'quoteDate').disabled = true;
        this.list.find(x => x.fieldName === 'wu11').disabled = true;
        this.newBtnDisabled = true; // 新建
        this.obsoleteBtnDisabled = false; // 作废
        this.saveBtnDisabled = false; // 保存
        this.cancelBtnDisabled = false; // 取消
        this.prindfBtnDisabled = false; // 打印
        this.completeBtnDisabled = false; // 完成
        this.importSalesOrderBtnDisabled = true; // 引进销售单
        this.exportSalesOrderBtnDisabled = false; // 导出销售单
      } else if (val == 'prindf') {
        // 打印
        console.log('printdf-----------');
        this.printFlag = true;
        this.$nextTick(() => {
          this.$refs.print.EXCUTE_PRINT();
        });
      } else if (val == 'cancel') {
        // 取消
        this.newBtnDisabled = false; // 新建
        this.obsoleteBtnDisabled = true; // 作废
        this.saveBtnDisabled = true; // 保存
        this.cancelBtnDisabled = false; // 取消
        this.prindfBtnDisabled = true; // 打印
        this.completeBtnDisabled = true; // 完成
        this.delDisabled = false;
        this.addBtnDisabled = true; // 新增
        this.exportBtnDisabled = true; // 导出
        this.importSalesOrderBtnDisabled = false; // 引进销售单
        this.exportSalesOrderBtnDisabled = true; // 导出销售单

        this.list.find(x => x.fieldName === 'quoteNo').disabled = false;
        this.list.find(x => x.fieldName === 'customerName').disabled = true;
        // this.list.find(x => x.fieldName === 'customerCar').disabled = true;
        this.list.find(x => x.fieldName === 'quoteDate').disabled = false;
        this.list.find(x => x.fieldName === 'wu11').disabled = false;
        this.columns.find(x => x.dataIndex === 'outPrice').disabled = false;
        this.columns.find(x => x.dataIndex === 'outQuantity').disabled = false;
        this.dataSource = [];
        this.$refs.form.RESET_FORM();
      }
      //  else if (val == 'complete') {
      //   //完成
      // }
    },
    exportFun() {
      this.exportLoading = true;
      partSalesQteExport(this.list.find(x => x.fieldName === 'quoteNo').initialValue).then(res => {
        exportExcelFile(res, '配件销售报价');
        this.exportLoading = false;
      });
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJBJ'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
        this.printParams.vDirectPrint = this.printParams.vDirectPrint === 0 ? '0' : this.printParams.vDirectPrin;
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style scoped lang="less">
.btn-group {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}
</style>
